import random
from multiprocessing.pool import ThreadPool, ApplyResult
import time
from common.utility import Utility

# 主函数
def main(thread_count: int = 5, sync: bool = True):
    Utility.print_info('entered.')
    results: list[ApplyResult] = []
    with ThreadPool(initializer=threadpool_init) as pool:
        for i in range(thread_count):
            if sync:
                start_thread_sync(pool)
            else:
                results.append(start_thread_async(pool))
        if not sync:
            for result in results:
                #result.wait()
                Utility.print_info(f'线程返回结果：{result.get()}')
    Utility.print_info('exited.')

# 同步创建线程
def start_thread_sync(pool: ThreadPool) -> None:
    sleep_time: int = int(random.random()*10)
    pool.apply(task, (sleep_time,))

# 异步创建线程
def start_thread_async(pool: ThreadPool) -> ApplyResult:
    sleep_time: int = int(random.random() * 10)
    return pool.apply_async(task, (sleep_time,), callback=callback, error_callback=error_callback)

# 线程池初始化
def threadpool_init() -> None:
    Utility.print_info('线程池初始化。')

# 线程池回调函数
def callback(_) -> None:
    Utility.print_info(f'线程池回调函数。{_}')

# 线程池错误回调函数
def error_callback(ex: BaseException) -> None:
    Utility.print_info(f'线程池错误回调函数：{ex}')

# 任务
def task(sleep_time: int) -> int:
    Utility.print_info(f'entered. It will sleep {sleep_time} seconds.')
    time.sleep(sleep_time)
    Utility.print_info('exited.')
    return sleep_time

main(2, sync=False)
